package com.ch.mapdemo.util;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *  数据同步 传送  接受方法在最下面
 * @author Administrator
 *
 */
public class HttpClientHelper {
    private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);

    
    public HttpClientHelper() {

    }
    public static final  String smHttpPath ="http://192.168.10.68:8080/MVN_AO/";
    /**
     * 发起POST请求
     *
     * @param urlName  具体的Action  和方法
     * @param paramJson 参数的json格式
     */
    public String sendPost(String urlName, String paramJson) {
    	//根据实际地址修改
    	//String smHttpPath ="http://localhost:8099/MVN_AO/";
    	//String url =  smHttpPath + urlName;
    	//String url =  "http://localhost:8088/oa/"+urlName+".action";
        logger.info("开始发起POST请求，请求地址为{}，参数为{}", urlName, paramJson);

        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建post请求方法实例对象
        PostMethod postMethod = new PostMethod(urlName);
        // 设置post请求超时时间
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        try {
            //json格式的参数解析
            RequestEntity entity = new StringRequestEntity(paramJson, "application/json", "UTF-8");
            postMethod.setRequestEntity(entity);

            httpClient.executeMethod(postMethod);
            String result = postMethod.getResponseBodyAsString();
            postMethod.releaseConnection();
            return result;
        } catch (IOException e) {
        		e.getMessage();
           // logger.error("POST请求发出失败，请求的地址为{}，参数为{}，错误信息为{}", url, paramJson);
        }
        return null;
    }

    /**
     * 发起GET请求
     *
     * @param urlParam url请求，包含参数
     */
    public static String sendGet(String urlParam) {
        logger.info("开始发起GET请求，请求地址为{}", urlParam);
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建GET请求方法实例对象
        GetMethod getMethod = new GetMethod(urlParam);
        // 设置post请求超时时间
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        getMethod.addRequestHeader("Content-Type", "application/json");
        try {
            httpClient.executeMethod(getMethod);
            String result = getMethod.getResponseBodyAsString();
            getMethod.releaseConnection();
          //  logger.info("返回信息为{}", result);
            return result;
        } catch (IOException e) {
        	e.getMessage();
         //   logger.error("GET请求发出失败，请求的地址为{}，错误信息为{}", urlParam,e);
        }
        return null;
    }
    /**
	 *  附件公文同步
	 * @param url
	 * @param files
	 * @return
	 */
	 public static Map<String, Object> uploadFileByHttpPost(String urlName, File files,String accessory){
		 //String bmHttpPath =PropertyPlaceholder.getProperty("smhHttpPath").toString();
		 String url =  smHttpPath + urlName+".action";
		// String url =  "http://localhost:8088/oa/"+urlName+".action" ;
		 Map<String, Object> resultMap = new HashMap<String, Object>();
	        CloseableHttpClient httpClient = HttpClients.createDefault();
	        try {
				 //把一个普通参数和文件上传给下面这个api接口
				 HttpPost httpPost = new HttpPost(url);
				 //设置传输参数,设置编码。设置浏览器兼容模式，解决文件名乱码问题
				 MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
				 FileBody fundFileBin = new FileBody(files, ContentType.MULTIPART_FORM_DATA);
				 ContentType contentType = ContentType.create("text/plain",Charset.forName("UTF-8"));
				 //相当于<input type="file" name="media"/>
				 multipartEntity.addPart("file", fundFileBin);
				 
				 
				 multipartEntity.addTextBody("accessory", accessory,contentType);
				 HttpEntity reqEntity = multipartEntity.build();
				 httpPost.setEntity(reqEntity);
				 //发起请求 并返回请求的响应
				 CloseableHttpResponse response = httpClient.execute(httpPost);
				
				 try {
				  //打印响应状态
				  resultMap.put("statusCode", response.getStatusLine().getStatusCode());
				  //获取响应对象
				  HttpEntity resEntity = response.getEntity();
				  if (resEntity != null) {
				      //打印响应内容
				      resultMap.put("data", EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
				  }
				  //销毁
				  EntityUtils.consume(resEntity);
				 } catch (Exception e) {
				  e.printStackTrace();
				 } finally {
				  response.close();
				 }
	        } catch (ClientProtocolException e1) {
	            e1.printStackTrace();
	            resultMap.put("statusCode", "404");
	        } catch (IOException e1) {
	            e1.printStackTrace();
	            resultMap.put("statusCode", "404");
	        } finally {
	            try {
	                httpClient.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        return resultMap;
	 }
	 	//这是接收参数 的方法
		/*
		 * public StringBuilder getPostRequestStream() throws
		 * UnsupportedEncodingException, IOException { HttpServletRequest request =
		 * ServletActionContext.getRequest(); InputStreamReader is = null; is = new
		 * InputStreamReader(request.getInputStream(), request.getCharacterEncoding());
		 * BufferedReader reader = new BufferedReader(is); // 将json数据放到String中
		 * StringBuilder sb = new StringBuilder(); String line = null; while ((line =
		 * reader.readLine()) != null) { sb.append(line); } return sb; }
		 */
 
}